package leetcode.剑指offer.前40;

import leetcode.剑指offer.pojo.TreeNode;
import org.junit.Test;

import java.util.*;

/**
 * @author :songyaozhang
 * @date :Created 2021/7/29 16:25
 * @description :
 */
public class 剑指_32_从上到下打印二叉树III {
    @Test
    public void test() {
        Solution solution = new Solution();

    }


    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            ArrayList<List<Integer>> ans = new ArrayList<>();
            if (root == null) return ans;
            int floor = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()) {
                int size = queue.size();
                ArrayList<Integer> list = new ArrayList<>();
                while (size > 0) {
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                    size--;
                }
                if (floor++ % 2 == 1) {
                    Collections.reverse(list);
                }
                ans.add(list);
            }
            return ans;
        }
    }


}
